package com.zhijian.medical.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.zhijian.medical.dao.local.RoutineQcHandleMapper;
import com.zhijian.medical.entity.dto.PersonDto;
import com.zhijian.medical.entity.po.RoutinePatient;
import com.zhijian.medical.entity.po.RoutineQcHandle;
import com.zhijian.medical.entity.vo.request.RoutinePatientSearchVo;
import com.zhijian.medical.entity.vo.request.RoutineQcHandleSearchVo;
import com.zhijian.medical.entity.vo.request.RoutineSampleSearchVo;
import com.zhijian.medical.entity.vo.response.RoutinePatientVo;
import com.zhijian.medical.entity.vo.response.RoutineQcSampleVo;
import com.zhijian.medical.entity.vo.response.RoutineSampleVo;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.util.page.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 剩余组织处理
 */
@Service
public class RoutineQcHandleService {

    @Autowired
    CacheService cacheService;

    @Autowired
    RoutineQcHandleMapper routineQcHandleMapper;

    @Autowired
    RoutinePatientService routinePatientService;

    @Autowired
    private RoutineSampleService sampleService;

    public Page<RoutineQcHandle> selectPage(RoutineQcHandleSearchVo routineQcHandleSearchVo){
        PageHelper.startPage(routineQcHandleSearchVo.getPageNum(), routineQcHandleSearchVo.getPageSize());
        com.github.pagehelper.Page<RoutineQcHandle> initData =
                routineQcHandleMapper.selectPageList(routineQcHandleSearchVo);
        List<Long> qcIdList = initData.getResult().stream().map(RoutineQcHandle::getQcId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(qcIdList)){
            checkData(qcIdList);
            PageHelper.startPage(routineQcHandleSearchVo.getPageNum(), routineQcHandleSearchVo.getPageSize());
            com.github.pagehelper.Page<RoutineQcHandle> resultOrg =
                    routineQcHandleMapper.selectPageList(routineQcHandleSearchVo);
            Page<RoutineQcHandle> result =
                    new com.zhijian.util.page.Page<>(true,
                            Integer.parseInt( String.valueOf(resultOrg.getTotal())), routineQcHandleSearchVo.getPageNum(), routineQcHandleSearchVo.getPageSize());
            result.setData(resultOrg.getResult());
            return result;
        }
        return new Page<>();
    }

    public void checkData(List<Long> qcIdList){
        QueryWrapper<RoutineQcHandle> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("qc_id", qcIdList);
        List<RoutineQcHandle> routineQcHandles =  routineQcHandleMapper.selectList(queryWrapper);
        if (routineQcHandles.size() != qcIdList.size()){
            Map<Long, RoutineQcHandle> existNode = routineQcHandles.stream().collect(Collectors.toMap(RoutineQcHandle::getQcId, e->e));
            List<Long> needGenerate = new LinkedList<>();
            for (Long qcid : qcIdList){
                if (!existNode.containsKey(qcid)){
                    needGenerate.add(qcid);
                }
            }
            for (Long qcId : needGenerate){
                addRoutineQcHandle(qcId);
            }
        }
    }

    public Page<RoutineSampleVo> readQcDetail(Long id, RoutineQcHandleSearchVo param){
        RoutineQcHandle routineQcHandle = routineQcHandleMapper.selectOne(id);
        RoutineSampleSearchVo searchVo = RoutineSampleSearchVo.builder().conventionPathologyNumber(routineQcHandle.getBlh()).build();
        RoutinePatientVo routinePatient = routinePatientService.selectOne(RoutinePatientSearchVo.builder().conventionPathologyNumber(routineQcHandle.getBlh()).build());
        searchVo.setPageNum(param.getPageNum());
        searchVo.setPageSize(param.getPageSize());
        Page<RoutineSampleVo> routineSampleVos = sampleService.selectPage(searchVo);
        for (RoutineSampleVo sampleVo : routineSampleVos.getData()){
            sampleVo.setNote(routinePatient.getName());
        }
        return routineSampleVos;
    }

    public void addRoutineQcHandle(Long qcId){
        RoutineQcHandle routineQcHandle = generateBasicData(qcId);
        routineQcHandleMapper.insert(routineQcHandle);
    }

    private RoutineQcHandle generateBasicData(Long qcId){
        int year = LocalDate.now().getYear();
        String key = "syzhcl_redis_prefix_" + year;
        RoutineQcHandle routineQcHandle = new RoutineQcHandle();
        routineQcHandle.setQcId(qcId);
        routineQcHandle.setState(0);
        Long code = cacheService.incr(key);
        String queueCode = StringUtils.leftPad(String.valueOf(code), 5, '0');
        routineQcHandle.setBatchNo("S" + year + queueCode);
        return routineQcHandle;
    }

    public RoutineQcHandle handleById(Long id){
        Date now = new Date();
        PersonDto personDto = CurrentUserHolder.getUser();
        RoutineQcHandle old = routineQcHandleMapper.selectById(id);
        RoutineQcHandle upd = new RoutineQcHandle();
        upd.setOperateId(personDto.getId());
        upd.setOperater(personDto.getName());
        upd.setState(1);
        upd.setId(old.getId());
        upd.setHandleTime(now);
        routineQcHandleMapper.updateById(upd);
        return old;
    }

    public RoutineQcHandle handle(Long qcId){
        PersonDto personDto = new PersonDto();
        QueryWrapper<RoutineQcHandle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("qc_id", qcId);
        RoutineQcHandle old = routineQcHandleMapper.selectOne(queryWrapper);
        if (old == null){
            RoutineQcHandle routineQcHandle = generateBasicData(qcId);
            routineQcHandle.setOperateId(personDto.getId());
            routineQcHandle.setOperater(personDto.getName());
            routineQcHandle.setState(1);
            routineQcHandleMapper.insert(routineQcHandle);
        }else {
            RoutineQcHandle upd = new RoutineQcHandle();
            upd.setOperateId(personDto.getId());
            upd.setOperater(personDto.getName());
            upd.setState(1);
            upd.setId(old.getId());
            routineQcHandleMapper.updateById(upd);
        }
        return old;
    }
}
